package com.olympus.hermes.common.advice;

import com.olympus.hermes.common.bean.Result;
import com.olympus.hermes.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Mickey
 * @since 2021/1/21
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        log.error("数据校验不通过：{}", e.getMessage());
        Map<String, String> errorMap = new LinkedHashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return Result
                .builder()
                .message("数据校验不通过")
                .status(HttpStatus.BAD_REQUEST.value())
                .data(errorMap)
                .success(false)
                .build();
    }

    @ExceptionHandler(value = BusinessException.class)
    public Result handleException(BusinessException e) {
        e.printStackTrace();
        log.error("异常：{}", e.getMessage());
        return Result
                .builder()
                .status(e.getMsg().getCode())
                .success(false)
                .message(e.getMsg().getName())
                .build();
    }

    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        log.error("异常：{}", e.getMessage());
        return Result
                .builder()
                .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .success(false)
                .build();
    }
}
